﻿<%@ WebHandler Language="C#" Class="HandlerProducts" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;


public class HandlerProducts : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        string status = context.Request.QueryString["status"];
        string strConn = UserClass.strconn;

        switch (status)
        {
            case "prosAnalysis":
                int categoryID = int.Parse(context.Request.QueryString["c_id"]);
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    string strCmd = @"SELECT product_name, SUM([count]) AS [count] FROM
                                                    (SELECT pp.product_name, pp.category_id, fb.unboxing_article_id, COUNT(*) AS [count], ua.product_id FROM user_favorite_box AS fb
                                                    INNER JOIN unboxing_article AS ua ON fb.unboxing_article_id = ua.unboxing_article_id 
                                                    INNER JOIN production_product AS pp ON ua.product_id = pp.product_id
                                                    WHERE pp.category_id = @c_id
                                                    GROUP BY fb.unboxing_article_id,ua.product_id,pp.product_name,pp.category_id) AS temp
                                                    GROUP BY product_id,product_name";
                    using (SqlDataAdapter da = new SqlDataAdapter(strCmd, conn))
                    {
                        da.SelectCommand.Parameters.AddWithValue("@c_id", categoryID);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "Products");
                        context.Response.ContentType = "application/json";
                        context.Response.Write(JsonConvert.SerializeObject(ds));
                        conn.Close();
                    }
                }
                break;
            case "cpAnalysis":
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    List<int> cpList = new List<int>();
                    int count = int.Parse(context.Request.QueryString["count"]);
                    int categoryId = int.Parse(context.Request.QueryString["c_id"]);
                    string table = "compare_" + count + "_products";
                    string strCmd = @"SELECT TOP 5 cp.*, pp.category_id
                                                            FROM " + table + @" as cp INNER JOIN
                                                            production_product as pp ON cp.product_1 = pp.product_id
                                                            WHERE category_id = @c_id
                                                            ORDER BY [count] DESC";
                    using (SqlCommand cmd = new SqlCommand(strCmd, conn))
                    {
                        cmd.Parameters.AddWithValue("@c_id", categoryId);
                        conn.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            for (int i = 1; i <= count; i++)
                            {
                                cpList.Add(Convert.ToInt32(reader[i]));
                            }
                        }
                        conn.Close();
                    }
                    List<ProductPreview> pps = new List<ProductPreview>();
                    conn.Open();
                    for (int i = 0; i < cpList.Count; i++)
                    {
                        
                        string strCmd2 = @"SELECT production_product.product_id AS id, production_product.product_name AS name, production_image.[image]
                                                    FROM production_product INNER JOIN
                                                               production_image ON production_product.product_id = production_image.product_id AND 
                                                               production_product.product_id = production_image.product_id
                                                    WHERE (production_image.image_order = 1) AND production_image.product_id = @p_id";
                        using (SqlCommand cmd = new SqlCommand(strCmd2, conn))
                        {
                            cmd.Parameters.AddWithValue("@p_id", cpList[i]);

                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    ProductPreview pp = new ProductPreview();
                                    pp.ID = Convert.ToInt32(reader["id"]);
                                    pp.Name = reader["name"].ToString();
                                    pp.Image = (byte[])reader["image"];
                                    pps.Add(pp);
                                }
                            }
                        }
                    }
                    conn.Close();
                    context.Response.ContentType = "application/json";
                    context.Response.Write(JsonConvert.SerializeObject(pps));
                    break;
                }
        }
    }

    private byte[] ObjectToByteArray(Object obj)
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}